/**
 * \* Created with IntelliJ IDEA.
 * \* User: 冯若航
 * \* Date: 2021/6/4
 * \* Time: 19:42
 * \* To change this template use File | Settings | File Templates.
 * \* Description:
 * \
 */
public class 二叉搜索树中第K小的元素 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public int kthSmallest(TreeNode root, int k) {
        traverse(root,k);
        return res;
    }

    //记录结果
    int res=0;
    //记录当前元素排名
    int rank=0;
    void traverse(TreeNode root,int k){
        if(root==null){
            return ;
        }
        traverse(root.left,k);
        rank++;
        if(k==rank){
            res=root.val;
            return;
        }
        traverse(root.right,k);
    }
}